#include "protocol.h"

/*
default function init, avoid run error if not register
*/
uint8_t proHandler(pmesg_prot pmesg)
{
	return 0;
}
uint8_t rxtxHandler(void)
{
	return 0;
}

list_prot 	mesg_queue_prot[MesgGroupMax];
func_prot 	func_register[MesgGroupMax] = 
{
	{rxtxHandler, rxtxHandler, proHandler},
	{rxtxHandler, rxtxHandler, proHandler},
	{rxtxHandler, rxtxHandler, proHandler},
	{rxtxHandler, rxtxHandler, proHandler},
	{rxtxHandler, rxtxHandler, proHandler},
	{rxtxHandler, rxtxHandler, proHandler}
};

void func_register_init(uint8_t Group, FunType rxFunc, FunType txFunc,FunType_para1 proFunc)
{
	func_register[Group].rxFunc = rxFunc;
	func_register[Group].txFunc = txFunc;
	func_register[Group].proFunc = proFunc;
}

void list_insert(pmesg_prot pmesg, uint8_t MesgGroup)
{
	uint8_t pos, status, len, i;
	plist_prot pqueue;
	pqueue = &mesg_queue_prot[MesgGroup];
	pos = pqueue->head;
	if(mesg_max==pos)pos = 0;
	status = pmesg->status;
	if(0==status){
		len = pmesg->len;
		pqueue->mesg_queue[pos].len = len;
		pqueue->mesg_queue[pos].status = status;
		pqueue->mesg_queue[pos].ID = pmesg->ID;
		for(i=0; i<len; i++){
			pqueue->mesg_queue[pos].buffer[i] = pmesg->buffer[i];
		}
		pqueue->head++;
		if(mesg_max==pqueue->head)pqueue->head=0;
		if(pqueue->size<10)pqueue->size++;		
	}
}



uint8_t list_check(uint8_t MesgGroup)
{
	uint8_t result;
	uint8_t pos;
	plist_prot pqueue;
	//first, rx data check
	result = func_register[MesgGroup].rxFunc();
	//second, rx data pro
	pqueue = &mesg_queue_prot[MesgGroup];
	//size = pqueue->size;
	if(pqueue->size>0){
	//while(pqueue->size>0){
		pos = pqueue->tail;
		if(pos>=mesg_max)pos=0;
		//result = protocol_process(pqueue->mesg_queue[pos]);
		//result pro
		result = func_register[MesgGroup].proFunc(&(pqueue->mesg_queue[pos]));
		pqueue->tail++;
		if(pqueue->tail>=mesg_max)pqueue->tail=0;		
		pqueue->size--;		
	}
	//third, tx data pro
	result = func_register[MesgGroup].txFunc();
	return result;
}
